package com.iraytek.rtsplib;


import pedro.encoder.Frame;
import pedro.encoder.video.GetVideoData;
import pedro.encoder.video.VideoEncoder;

public class CameraVideoEncoder extends VideoEncoder {
    public CameraVideoEncoder(GetVideoData getVideoData) {
        super(getVideoData);
    }

    @Override
    protected Frame getInputFrame() throws InterruptedException {
        Frame frame = queue.take();
        if (fpsLimiter.limitFPS()) {
            return getInputFrame();
        }
        if (getRotation() != 0) {
            frame.setBuffer(rotate(frame.getBuffer(), getWidth(), getHeight(), getRotation()));
        }
        return frame;
    }


    /**
     * rotate image, default implementation is rotate 90,
     * override it if other degree is needed
     *
     * @param b      yuv data, the format should be "YYYYUVUV"
     * @param width  original width of image
     * @param height original height
     * @param degree degree to rotate, should be in {90,180,270}
     * @return rotated yuv data
     */
    protected byte[] rotate(byte[] b, int width, int height, int degree) {
        if (degree == 90) {
            byte[] data = new byte[b.length];
            int i = 0;
            for (int x = 0; x < width; x++) {
                for (int y = height - 1; y >= 0; y--) {
                    data[i++] = b[y * width + x];
                }
            }
            int offset = width * height;

            for (int x = 0; x < width; x += 2) {
                for (int y = height / 2 - 1; y >= 0; y--) {
                    int index = offset + y * width + x;
                    data[i++] = b[index];
                    data[i++] = b[index + 1];
                }
            }

            return data;
        }
        return b;
    }

}
